// 2013-10-6上午11:05:23  net.betou.core.service.post.impl.PostImpl.java

package net.betou.core.service.post.impl;

import net.betou.core.service.post.Post;
import net.betou.core.service.post.PostKeyVal;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;
import org.jsoup.Connection.KeyVal;
import org.springframework.stereotype.Component;

/**
 * 
 * @author 叶装装
 */
@Component
public  class PostImpl implements Post{

	private static final Logger log = Logger.getLogger( PostImpl.class );
	
	private String ipList; // ip列表， 未经拆分的
	private KeyVal keyVal; // 值列表

	public PostImpl( ){}
	
	public void run( ) {
		
		String [ ] ipAddrs = getIpArray( );
		
		if( ipAddrs == null || ipAddrs.length == 0 ){
			return;
		}
		
		log.info( "发送数据==================:" + keyVal.value( ) );
		
		DefaultHttpClient httpClient = new DefaultHttpClient( );
		
		setParams( httpClient, CoreConnectionPNames.CONNECTION_TIMEOUT, 300 ); // 单位毫秒, // 连接超时
		setParams( httpClient, CoreConnectionPNames.SO_TIMEOUT, 500 ); // 单位毫秒, // 发送数据超时
		
		try{
			for ( int i = 0; i < ipAddrs.length; i++ ){
				String ip = ipAddrs[ i ];

				HttpPost httpost = new HttpPost( ip );
				StringEntity myEntity = new StringEntity( PostKeyVal.DEFAULT_POST_KEY + "=" + keyVal.value( ), ContentType.create( "text/plain", "GBK" ) );

				httpost.setEntity( myEntity );
				try{
					httpClient.execute( httpost );
				}catch( Exception e ){
					String msg = e.getMessage( );
					if( "!Read timed out".equals( msg ) ){
						e.printStackTrace( );
					}
				}
			}
		}catch( Exception e ){
			e.printStackTrace( );
		}finally{
			httpClient.getConnectionManager( ).shutdown( );
		}
	}
	
	private String [ ] getIpArray( ){
		if( StringUtils.isBlank( ipList ) ){
			return null;
		}
		
		return StringUtils.split( ipList, "," );
	}

	private void setParams( DefaultHttpClient httpClient, String name, Object value ){
		HttpParams httpParams = httpClient.getParams( );
		httpParams.setParameter( name, value );
	}
	
	public void setIpList( String ipList ) {
		this.ipList = ipList;
	}

	public void setKeyVal( KeyVal keyVal ) {
		this.keyVal = keyVal;
	}

	// 该方法不做任何事情
	public void setMobiles( String mobiles ) {
	}
}
